package com.gcloud.controller.network.handler.api.securitygroup.standard;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.gcloud.common.model.PageParams;
import com.gcloud.controller.network.service.ISecurityGroupService;
import com.gcloud.controller.utils.ApiUtil;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.core.handle.ApiHandler;
import com.gcloud.core.handle.MessageHandler;
import com.gcloud.core.util.BeanUtil;
import com.gcloud.framework.db.PageResult;
import com.gcloud.header.ApiVersion;
import com.gcloud.header.Module;
import com.gcloud.header.SubModule;
import com.gcloud.header.network.model.SecurityGroupItemType;
import com.gcloud.header.network.model.standard.StandardSecurityGroupItemType;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeSecurityGroupsMsg;
import com.gcloud.header.network.msg.api.standard.StandardApiDescribeSecurityGroupsReplyMsg;

@ApiHandler(module=Module.ECS,subModule=SubModule.SECURITYGROUP,action="DescribeSecurityGroups", versions = {ApiVersion.Standard})
public class StandardApiDescribeSecurityGroupsHandler extends MessageHandler<StandardApiDescribeSecurityGroupsMsg, StandardApiDescribeSecurityGroupsReplyMsg>{

	@Autowired
	ISecurityGroupService securityGroupService;
	
	@Override
	public StandardApiDescribeSecurityGroupsReplyMsg handle(StandardApiDescribeSecurityGroupsMsg msg)
			throws GCloudException {
		PageParams params = BeanUtil.copyProperties(msg, PageParams.class);
        PageResult<SecurityGroupItemType> response = securityGroupService.describeSecurityGroups(params, msg.getCurrentUser());
        PageResult<StandardSecurityGroupItemType> stdResponse = ApiUtil.toPage(response, toStandardReply(response.getList()));
        
        StandardApiDescribeSecurityGroupsReplyMsg replyMsg = new StandardApiDescribeSecurityGroupsReplyMsg();
        replyMsg.init(stdResponse);
        return replyMsg;
	}
	
	private List<StandardSecurityGroupItemType> toStandardReply(List<SecurityGroupItemType> list) {
		if(null == list) {
			return null;
		}
		
		List<StandardSecurityGroupItemType> stdList = new ArrayList<>();
		
		for (SecurityGroupItemType item : list) {
			StandardSecurityGroupItemType tmp = BeanUtil.copyProperties(item, StandardSecurityGroupItemType.class);
			stdList.add(tmp);
		}
		return stdList;
		
	}

}
